package com.wushijia.java8.concurrent;

import static java.util.concurrent.Executors.newFixedThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.StampedLock;

/**
 * 通过lock.validate(stamp)检查标记是否有效
 *
 * @author Benjamin Winterberg
 */
public class Lock5 {

  public static void main(String[] args) {
    ExecutorService executor = newFixedThreadPool(2);

    StampedLock lock = new StampedLock();

    executor.submit(() -> {
      long stamp = lock.tryOptimisticRead();
      try {
        System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
        ConcurrentUtils.sleep(1);
        System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
        ConcurrentUtils.sleep(2);
        System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
      } finally {
        lock.unlock(stamp);
      }
    });

    executor.submit(() -> {
      long stamp = lock.writeLock();
      try {
        System.out.println("Write Lock acquired");
        ConcurrentUtils.sleep(2);
      } finally {
        lock.unlock(stamp);
        System.out.println("Write done");
      }
    });

    ConcurrentUtils.stop(executor);
  }

}
